﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.FP;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness.DTO;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.FP
{
    public partial class Base_OverFlowLogBusiness : BaseBusiness<Base_OverFlowLog>, IBase_OverFlowLogBusiness, ITransientDependency
    {
        public Base_OverFlowLogBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<Base_OverFlowLog>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_OverFlowLog>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_OverFlowLog, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_OverFlowLog> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Base_OverFlowLog data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Base_OverFlowLog data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<Base_OverFlowLoglist> GetOverFlowLoglist(string BillId, string OverFlowId,string Type)
        {
            Base_OverFlowLoglist base_OverFlowLoglist = new Base_OverFlowLoglist();

            var PB_DesignList = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == BillId).FirstOrDefaultAsync();
            if (PB_DesignList != null)
            {
                List<Base_OverFlowLoglist> base_OverFlowLoglists = new List<Base_OverFlowLoglist>();

                Expression<Func<Base_OverFlowLog, Base_User, PB_DesignList, PB_Project, PB_Buildingnumber, PB_DesignListFile, mainData>> select = (a, b, c, d, e, f) => new mainData
                {
                    ApprovedName = b.RealName,
                    ApprovalTime = a.CreateTime,
                    BillId = c.Id,
                    ProjectName = d.Name,
                    ContractNo = c.ContractNo,
                    Remarks = a.Remark,
                    Reason = a.Reason,
                    ProjectAddress = c.ProjectAddress,
                    LiftingMode = c.LiftingMode,
                    Salesman = c.Salesman,
                    Phone0 = c.Phone0,
                    StepHeight = c.StepHeight,
                    Receiver = c.Receiver,
                    Phone1 = c.Phone1,
                    Color = c.Color,
                    InDate = Convert.ToString(c.InDate),
                    DesignFileUrl = f.DetailedFile,
                    OverFlowId = a.OverFlowId,
                    IssueDate = c.CreateTime,
                    DesignName = c.ProjectName,
                    GongchengName = c.Name,
                    DeliveryNoticeType = f.Type.ToString(),
                    

                };
                select = select.BuildExtendSelectExpre();
                var q = from a in GetIQueryable().AsExpandable()
                        join b in Db.GetIQueryable<Base_User>() on a.CreatorId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_DesignList>() on a.BillId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        join d in Db.GetIQueryable<PB_Project>() on c.ProjectId equals d.Id into cd
                        from d in cd.DefaultIfEmpty()
                        join e in Db.GetIQueryable<PB_Buildingnumber>() on c.BuildingNumberID equals e.Id into ce
                        from e in ce.DefaultIfEmpty()
                        join f in Db.GetIQueryable<PB_DesignListFile>() on c.Id equals f.DesignId into cf
                        from f in cf.DefaultIfEmpty()
                        select @select.Invoke(a, b, c, d, e, f);

                q = q.Where(x => x.BillId == BillId&&x.OverFlowId==OverFlowId&&x.DeliveryNoticeType==Type).OrderBy(x => x.ApprovalTime);
               
                    base_OverFlowLoglist.main = q.ToList();
               
               
                return base_OverFlowLoglist;
            }
      
            //申请人查看钉钉审批列表
            var PB_DeliveryNoticeIsNull = await Db.GetIQueryable<PB_DeliveryNotice>().Where(m => m.Id == BillId).FirstOrDefaultAsync();
                if (PB_DeliveryNoticeIsNull != null) {
                    List<Base_OverFlowLoglist> base_OverFlowLoglists = new List<Base_OverFlowLoglist>();

                    Expression<Func<Base_OverFlowLog, Base_User, PB_DeliveryNotice, mainData>> select = (a, b, c) => new mainData

                    {
                        ApprovedName = b.RealName,
                        ApprovalTime = a.CreateTime,
                        BillId = c.Id,
                        ProjectName = c.ProjectName,
                        ContractNo = c.ContractNo,
                        SignUnitName = c.SignUnitName,
                        CooperativeUnitName = c.CooperativeUnitName,
                        SaleUnitName = c.SaleUnitName,
                        IssueDate = c.IssueDate,
                        Address = c.Address,
                        Remarks = a.Remark,
                        Reason = a.Reason,
                        OverFlowId = a.OverFlowId,
                        //发货通知
                        MobilizationNoticeType=c.TypeId,
                        DeliveryNoticeFreightDetails=c.FreightDetails,
                        DeliveryNoticerequirement=c.Remark,
                        DeliveryNoticeSettlementmethod=c.Remarks,
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in GetIQueryable().AsExpandable()
                            join b in Db.GetIQueryable<Base_User>() on a.CreatorId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_DeliveryNotice>() on a.BillId equals c.Id into ac
                            from c in ac.DefaultIfEmpty()
                            select @select.Invoke(a, b, c);


                    q = q.Where(x => x.BillId == BillId && x.OverFlowId == OverFlowId).OrderBy(x => x.ApprovalTime);

                    base_OverFlowLoglist.main = q.ToList();
                    var PB_DeliveryNoticeItem = Db.GetIQueryable<PB_DeliveryNoticeItem>().Where(m => m.ParentId == BillId).ToList();
                    List<Item> item = new List<Item>();
                    foreach (var i in PB_DeliveryNoticeItem)
                    {
                        Item item1 = new Item();
                        item1.InDate = i.InDate.ToString();
                        item1.BuidingNo = i.BuildingNo;
                        item.Add(item1);
                    }
                    base_OverFlowLoglist.Sub = item;

                    return base_OverFlowLoglist;
                }
                var PB_MobilizationNoticeIsNull = await Db.GetIQueryable<PB_MobilizationNotice>().Where(m => m.Id == BillId).FirstOrDefaultAsync();
                if (PB_MobilizationNoticeIsNull != null) {
                    List<Base_OverFlowLoglist> base_OverFlowLoglists = new List<Base_OverFlowLoglist>();

                    Expression<Func<Base_OverFlowLog, Base_User, PB_MobilizationNotice, mainData>> select = (a, b, c) => new mainData
                    {
                        ApprovedName = b.RealName,
                        ApprovalTime = a.CreateTime,
                        BillId = c.Id,
                        ProjectName = c.ProjectName,
                        ContractNo = c.ContractNo,
                        SignUnitName = c.SignUnitName,
                        CooperativeUnitName = c.CooperativeUnitName,
                        SaleUnitName = c.SaleUnitName,
                        IssueDate = c.IssueDate,
                        Remarks = a.Remark,
                        Reason = a.Reason,
                        OverFlowId = a.OverFlowId,
                        MobilizationNoticeType=c.TypeId,
                    };
                    select = select.BuildExtendSelectExpre();
                    var q = from a in GetIQueryable().AsExpandable()
                            join b in Db.GetIQueryable<Base_User>() on a.CreatorId equals b.Id into ab
                            from b in ab.DefaultIfEmpty()
                            join c in Db.GetIQueryable<PB_MobilizationNotice>() on a.BillId equals c.Id into ac
                            from c in ac.DefaultIfEmpty()
                            select @select.Invoke(a, b, c);


                    q = q.Where(x => x.BillId == BillId && x.OverFlowId == OverFlowId).OrderBy(x => x.ApprovalTime);
                    base_OverFlowLoglist.main = q.ToList();
                    var PB_DeliveryNoticeItem = Db.GetIQueryable<PB_MobilzationItem>().Where(m => m.ParentId == BillId).ToList();
                    List<Item> item = new List<Item>();
                    foreach (var i in PB_DeliveryNoticeItem) {
                        Item item1 = new Item();
                        item1.InDate = i.MobilizationTime.ToString();
                        item1.BuidingNo = i.BuildingNo;
                        item.Add(item1);
                    }
                    base_OverFlowLoglist.Sub = item;

                }
                return base_OverFlowLoglist;
            
           
        }

        public async Task<PageResult<ApprovalTask>> GetApprovalTaskList(PageInput<ConditionDTO> input)
        {
            StringBuilder sqlmain = new StringBuilder();
            sqlmain.AppendLine("SELECT * FROM(SELECT");
            sqlmain.AppendLine(" b.Id,");
            sqlmain.AppendLine(" a.OverFlowId,");
            sqlmain.AppendLine("b.Abstract PropjectName,");
            sqlmain.AppendLine("'发货通知' AS 'Title' ,");
            sqlmain.AppendLine(" b.CreateTime");
            sqlmain.AppendLine("FROM");
            sqlmain.AppendLine(" Base_OverFlowLog AS a");
            sqlmain.AppendLine("INNER JOIN PB_DeliveryNotice AS b ON a.BillId = b.Id");
            sqlmain.AppendLine("INNER JOIN PB_DeliveryNoticeItem AS c ON c.ParentId = b.Id");
            sqlmain.AppendLine("WHERE");
            sqlmain.AppendLine(" a.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+"' ) ");
            sqlmain.AppendLine("OR b.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+"' ) ");
            sqlmain.AppendLine("GROUP BY");
            sqlmain.AppendLine(" b.Id,");
            sqlmain.AppendLine(" a.OverFlowId UNION ALL");
            sqlmain.AppendLine("SELECT");
            sqlmain.AppendLine(" b.Id,");
            sqlmain.AppendLine("  a.OverFlowId, ");
            sqlmain.AppendLine(" b.Abstract PropjectName,");
            sqlmain.AppendLine("  '进场通知' AS 'Title' ,");
            sqlmain.AppendLine("b.CreateTime");
            sqlmain.AppendLine("FROM");
            sqlmain.AppendLine(" Base_OverFlowLog AS a");
            sqlmain.AppendLine(" INNER JOIN PB_MobilizationNotice AS b ON a.BillId = b.Id");
            sqlmain.AppendLine(" INNER JOIN PB_MobilzationItem AS c ON c.ParentId = b.Id");
            sqlmain.AppendLine("WHERE");
            sqlmain.AppendLine("  a.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+"' )");
            sqlmain.AppendLine("	OR b.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+ "' )GROUP BY  b.Id, a.OverFlowId  UNION ALL");
            sqlmain.AppendLine("SELECT");
            sqlmain.AppendLine("  b.Id,");
            sqlmain.AppendLine("a.OverFlowId,");
            sqlmain.AppendLine("b.ProjectName PropjectName,");
            sqlmain.AppendLine("CASE c.BillType  WHEN 'DesignList' THEN '设计清单' WHEN 'InsertDesignList' THEN '补加单' else '变更单' END Title,");
            sqlmain.AppendLine("b.CreateTime");
            sqlmain.AppendLine("FROM");
            sqlmain.AppendLine("  Base_OverFlowLog AS a");
            sqlmain.AppendLine(" INNER JOIN PB_DesignList AS b ON a.BillId = b.Id");
            sqlmain.AppendLine("INNER JOIN Base_OverFlow AS c ON a.OverFlowId=c.Id");
            sqlmain.AppendLine("WHERE");
            sqlmain.AppendLine(" a.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+"' )");
            sqlmain.AppendLine("OR b.CreatorId = (SELECT Id FROM Base_User WHERE DingUserId = '"+input.Search.Keyword+ "' )");
            sqlmain.AppendLine("GROUP BY");
            sqlmain.AppendLine(" b.Id,");
            sqlmain.AppendLine("a.OverFlowId) AS T ORDER BY T.CreateTime DESC");
            var res =await Db.GetListBySqlAsync<ApprovalTask>(sqlmain.ToString());

         

            int pagecount;//总页数
            List<ApprovalTask> listpro_down = res.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<ApprovalTask> productes = new List<ApprovalTask>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<ApprovalTask> { Data = productes, Total = pagees };
        }

        public async Task<List<DingDesignListCC>> GetDingDesignListCC(string BillId,string BillType)
        {
            if (BillType == "DesignList")
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine("SELECT");
                sql.AppendLine("d.`Name` ProjectName,");
                sql.AppendLine("a.ContractNo ContractNo,");
                sql.AppendLine("a.`Name` DesignName,");
                sql.AppendLine("a.ProjectName GongchengName,");
                sql.AppendLine("a.InDate InDate,");
                sql.AppendLine("e.DetailedFile DesignFileUrl");
                sql.AppendLine("FROM");
                sql.AppendLine("PB_DesignList AS a");
                sql.AppendLine("LEFT JOIN PB_Project AS d ON a.ProjectId = d.Id");
                sql.AppendLine("LEFT JOIN PB_DesignListFile AS e ON e.DesignId = a.Id and  e.Type=0");
                sql.AppendLine("WHERE");
                sql.AppendLine("a.Id = '" + BillId + "' ");
                var Listdata = await Db.GetListBySqlAsync<DingDesignListCC>(sql.ToString());
                return Listdata;
            }
            else if (BillType == "InsertDesignList") {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine("SELECT");
                sql.AppendLine("d.`Name` ProjectName,");
                sql.AppendLine("a.ContractNo ContractNo,");
                sql.AppendLine("a.`Name` DesignName,");
                sql.AppendLine("a.ProjectName GongchengName,");
                sql.AppendLine("a.InDate InDate,");
                sql.AppendLine("e.DetailedFile DesignFileUrl");
                sql.AppendLine("FROM");
                sql.AppendLine("PB_DesignList AS a");
                sql.AppendLine("LEFT JOIN PB_Project AS d ON a.ProjectId = d.Id");
                sql.AppendLine("LEFT JOIN PB_DesignListFile AS e ON e.DesignId = a.Id and  e.Type=1");
                sql.AppendLine("WHERE");
                sql.AppendLine("a.Id = '" + BillId + "' ");
                sql.AppendLine(" ORDER BY e.VersionNumber DESC LIMIT 1");
                var Listdata = await Db.GetListBySqlAsync<DingDesignListCC>(sql.ToString());
                return Listdata;
            } else if (BillType== "ChangeDesignList ") {
         
          
                    StringBuilder sql3 = new StringBuilder();
                sql3.AppendLine("SELECT");
                sql3.AppendLine("d.`Name` ProjectName,");
                sql3.AppendLine("a.ContractNo ContractNo,");
                sql3.AppendLine("a.`Name` DesignName,");
                sql3.AppendLine("a.ProjectName GongchengName,");
                sql3.AppendLine("a.InDate InDate,");
                sql3.AppendLine("e.DetailedFile DesignFileUrl");
                sql3.AppendLine("FROM");
                sql3.AppendLine("PB_DesignList AS a");
                sql3.AppendLine("LEFT JOIN PB_Project AS d ON a.ProjectId = d.Id");
                sql3.AppendLine("LEFT JOIN PB_DesignListFile AS e ON e.DesignId = a.Id and  e.Type=2");
                sql3.AppendLine("WHERE");
                sql3.AppendLine("a.Id = '" + BillId + "' ");
                sql3.AppendLine(" ORDER BY e.VersionNumber DESC LIMIT 1");
                    var Listdata = await Db.GetListBySqlAsync<DingDesignListCC>(sql3.ToString());
                    return Listdata;
                }

            return new List<DingDesignListCC>();
          

        }
    }

        #endregion

        #region 私有成员

        #endregion
    }
